package com.janushuang.algorithm.sorter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zhijing.huang
 *         Created by zhijing.huang on 2014/9/26.
 */
public class BubbleSorter<E extends Comparable<E>> extends Sorter<E> {
    private static final Logger LOG = LoggerFactory.getLogger(BubbleSorter.class);

    private static boolean DOWN = true;

    @Override
    public void sort(E[] data, int from, int len) {
        if (DOWN) {
            bubbleDownSort(data,from,len);
        } else {
            bubbleUpSort(data, from, len);
        }
    }

    private void bubbleUpSort(E[] data, int from, int len) {
        for (int i = from+len-1; i >=from; i--) {
            for (int j = from; j < i; j++) {
                if (data[j].compareTo(data[j+1])>0) {
                    swap(data,j,j+1);
                }
            }
        }
    }

    private void bubbleDownSort(E[] data, int from, int len) {
        for (int i = from; i <=from+len; i++) {
            for (int j = from+len-1; j > i; j--) {
                if (data[j].compareTo(data[j-1])>0) {
                    swap(data,j-1,j);
                }
            }
        }
    }

//    @Override
//    public void sort(int[] data) {
//        int loopCount=0;
//        for (int i = 0; i < data.length; i++) {
//            ++loopCount;
//            for (int j = data.length-1; j > i; j--) {
//                ++loopCount;
//                if(data[j]<data[j-1]) {
//                    SortUtils.swap(data,j,j-1);
//                }
//            }
//        }
////        LOG.info("loopCount={}",loopCount);
//    }
}
